package com.wbp.cms.core.sdk.image;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.wbp.cms.core.util.CommonProperties;
import com.wbp.cms.core.util.CommonUtil;


/**
 * @Description:
 * @Department:
 * @author andy.lhc
 * @date 2016年3月24日 下午8:26:51
 */
@Service("oSSImgYunService")
public class OSSImgYunServiceImpl implements OSSImgYunService {
  Logger logger = Logger.getLogger(OSSImgYunServiceImpl.class);

  private String accessKeyId = CommonProperties.getInstance().getProperties("ali_oss_accessKeyId");

  private String accessKeySecret = CommonProperties.getInstance().getProperties(
      "ali_oss_accessKeySecret");

  private String bucketName = CommonProperties.getInstance().getProperties("ali_oss_bucketName");

  private String domainName = CommonProperties.getInstance().getProperties("ali_oss_domainName");

  private String endpoint = CommonProperties.getInstance().getProperties("ali_oss_endpoint");

  private static OSSClient ossClient = null;

  private final String URL = "http://" + this.bucketName + "." + this.domainName;

  private final String baseUrl = CommonProperties.getInstance().getProperties("ali_oss_baseUrl");
 // private static final String DIR_ROOT = "/";

  public OSSImgYunServiceImpl() {
	  try{
		  
		  ossClient =
			        new OSSClient(this.endpoint, this.accessKeyId, this.accessKeySecret,
			            getClientConfiguration());

			    if (!ossClient.doesBucketExist(this.bucketName)) {
			      ossClient.createBucket(this.bucketName);
			    }
			    ossClient.setBucketAcl(this.bucketName, CannedAccessControlList.PublicRead);
			    
	  }catch(Exception e){
		  logger.error("OSSImgYunServiceImpl exception:",e);
	  }
    
  }

  private ClientConfiguration getClientConfiguration() {
    ClientConfiguration conf = new ClientConfiguration();

    conf.setMaxConnections(10);

    conf.setConnectionTimeout(5000);

    conf.setMaxErrorRetry(3);

    conf.setSocketTimeout(30000);

    return conf;
  }

  public Map<String, String> uploadFile(byte[] file, String fileName) throws IOException {
    InputStream is = new FileInputStream(CommonUtil.byte2File(file));
    ObjectMetadata objectMeta = new ObjectMetadata();
    objectMeta.setContentLength(file.length);

    objectMeta.setContentType("image/jpeg");
    String key = fileName;
    String filePath = "/" + key;
    try {
      ossClient.putObject(this.bucketName, key, is, objectMeta);

      return getUploadResult(true, filePath);
    } catch (Exception e) {
      this.logger.error("OSS upload error", e);
      return getUploadResult(false, filePath);
    } finally {
      if (is != null)
        is.close();
    }
  }

  public Map<String, String> uploadFile(File file, String fileName) throws IOException {
    ObjectMetadata objectMeta = new ObjectMetadata();
    objectMeta.setContentLength(file.length());

    objectMeta.setContentType("image/jpeg");
    InputStream input = null;

    String key = fileName;
    String filePath = "/" + key;
    try {
      input = new FileInputStream(file);
      ossClient.putObject(this.bucketName, key, input, objectMeta);
      return getUploadResult(true, filePath);
    } catch (Exception e) {
      this.logger.error("OSS upload error", e);
      return getUploadResult(false, filePath);
    } finally {
      if (input != null)
        input.close();
    }
  }

  public Map<String, String> uploadFile(byte[] file, String fileDirectory, String fileName)
      throws IOException {
    InputStream is = new FileInputStream(CommonUtil.byte2File(file));
    ObjectMetadata objectMeta = new ObjectMetadata();
    objectMeta.setContentLength(file.length);

    objectMeta.setContentType("image/jpeg");
    String key = fileDirectory;
    if (fileName.indexOf(".") > 0) {
      String prefix = fileName.substring(0, fileName.indexOf("."));
      String suffix = fileName.substring(fileName.indexOf("."), fileName.length());
      key = key + prefix + System.currentTimeMillis() + suffix;
    } else {
      key = key + fileName + System.currentTimeMillis() + ".jpg";
    }
    String filePath = "/" + key;
    try {
      ossClient.putObject(this.bucketName, key, is, objectMeta);

      return getUploadResult(true, filePath);
    } catch (Exception e) {
      this.logger.error("OSS upload error", e);
      return getUploadResult(false, filePath);
    } finally {
      if (is != null)
        is.close();
    }
  }

  public Map<String, String> uploadFile(File file, String fileDirectory, String fileName)
      throws IOException {
    ObjectMetadata objectMeta = new ObjectMetadata();
    objectMeta.setContentLength(file.length());

    objectMeta.setContentType("image/jpeg");
    InputStream input = null;

    String key = fileDirectory;
    if (fileName.indexOf(".") > 0) {
      String prefix = fileName.substring(0, fileName.indexOf("."));
      String suffix = fileName.substring(fileName.indexOf("."), fileName.length());
      key = key + prefix + System.currentTimeMillis() + suffix;
    } else {
      key = key + fileName + System.currentTimeMillis() + ".jpg";
    }
    String filePath = "/" + key;
    try {
      input = new FileInputStream(file);
      ossClient.putObject(this.bucketName, key, input, objectMeta);

      return getUploadResult(true, filePath);
    } catch (Exception e) {
      this.logger.error("OSS upload error", e);
      return getUploadResult(false, filePath);
    } finally {
      if (input != null)
        input.close();
    }
  }

  private Map<String, String> getUploadResult(boolean result, String filePath) {
    Map<String, String> map = new HashMap<String, String>();
    if (result) {
      map.put("status", "success");
      map.put("url", this.baseUrl + filePath);  //得到自定义域名地址
      map.put("ossurl", this.URL + filePath);   // 得到oss上的域名地址
    } else {
      map.put("status", "failure");
    }
    return map;
  }

  public Map<String, String> uploadFile(FileInputStream inputStream, String fileName)
      throws IOException {
    ObjectMetadata objectMeta = new ObjectMetadata();
    objectMeta.setContentLength(inputStream.available());

    objectMeta.setContentType("image/jpeg");

    String key = fileName;
    String filePath = "/" + key;
    try {
      ossClient.putObject(this.bucketName, key, inputStream, objectMeta);
      return getUploadResult(true, filePath);
    } catch (Exception e) {
      this.logger.error("OSS upload error", e);
    }
    return getUploadResult(false, filePath);
  }

  public Map<String, String> uploadFile(URL url, String fileName) throws IOException {
    String filePath = "/" + fileName;
    try {
      return uploadFile(new File(url.toURI()), fileName);
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    return getUploadResult(false, filePath);
  }

  public Map<String, String> uploadFile(FileInputStream inputStream, String fileDirectory,
      String fileName) throws IOException {
    ObjectMetadata objectMeta = new ObjectMetadata();
    objectMeta.setContentLength(inputStream.available());

    objectMeta.setContentType("image/jpeg");

    String key = fileDirectory;
    if (fileName.indexOf(".") > 0) {
      String prefix = fileName.substring(0, fileName.indexOf("."));
      String suffix = fileName.substring(fileName.indexOf("."), fileName.length());
      key = key + prefix + System.currentTimeMillis() + suffix;
    } else {
      key = key + fileName + System.currentTimeMillis() + ".jpg";
    }
    String filePath = "/" + key;
    try {
      ossClient.putObject(this.bucketName, key, inputStream, objectMeta);

      return getUploadResult(true, filePath);
    } catch (Exception e) {
      this.logger.error("OSS upload error", e);
    }
    return getUploadResult(false, filePath);
  }

  public Map<String, String> uploadFile(URL url, String fileDirectory, String fileName)
      throws IOException {
    String filePath = "/" + fileName;
    try {
      return uploadFile(new File(url.toURI()), fileDirectory, fileName);
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    return getUploadResult(false, filePath);
  }

   
}
